package com.maker.LMMS.service;

import com.alibaba.fastjson.JSONObject;
import com.blade.jdbc.core.ActiveRecord;
import com.blade.mvc.http.Request;
import com.blade.mvc.http.Response;
import com.blade.mvc.multipart.FileItem;
import com.maker.LMMS.hook.UserHook;
import com.maker.LMMS.model.*;

import javax.imageio.IIOException;
import javax.mail.MessagingException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Optional;


/**
 * @author : zimu
 * @Date: 2018/7/31 20:42
 * @description :
 */
public class UserImpl {

    //获取任务发布的时间
    Date  date =new Date();
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd  HH:mm:ss");
    String date1 = sdf.format(date);


    /**
     * @description :登录
     * @param email
     * @param password
     * @param request
     * @return
     */
    public boolean login(String email, String password, Request request) {
        Users users = new Users();
        Md5 md5 = new Md5();
        request.session().attribute("name", null);
        password = md5.getMd5(password);
        users.setM_email(email);
        users.setM_password(password);
        Users findResult = users.find();
        if(findResult!=null){
            findResult.setM_password("");
            request.session().attribute("name", findResult);

            return true;
        }
        else {
            return false;
        }
    }

    /**
     * @description: 退出登录
     * @param request
     */
    public void logout(Request request){
        request.session().remove("name");
    }

    public boolean updatePassword(String oldPassword, String newPassword, Request request) {
        Users user = new Users();
        Md5 md5 = new Md5();
        Users users  = request.session().attribute("name");
        oldPassword = md5.getMd5(oldPassword);
        user.setM_id(users.getM_id());
        user.setM_password(oldPassword);
        if (user.find()!=null) {

            newPassword = md5.getMd5(newPassword);
            user.setM_password(newPassword);
            user.where("m_id", "=", users.getM_id()).update();
            return true;
        }else {
            return false;
        }

    }

    public Integer checkPass(String email) {
        Users users = new Users();
        users.setM_email(email);
        users = users.find();
        if (users==null)
            return -2;
        return users.getM_flag();
    }

    /**
     * @description 用户注册
     * @param realname
     * @param email
     * @param password
     */
    public Integer signup(String realname, String email, String password) {
        Users users = new Users();
        Skills skills = new Skills();
        Md5 md5 = new Md5();
        password = md5.getMd5(password);
        users.setM_realname(realname);
        users.setM_password(password);
        users.setM_email(email);
        users.save();
        users = users.find();
        skills.execute("INSERT INTO skill VALUES(NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,?)",users.getM_id());
        return users.getM_id();
    }



    /**
     * @description 文件上传
     * @param request
     * @param avatar_data
     * @param response
     * @return
     */
    public String upload(Request request, String avatar_data, Response response){
        Optional<FileItem> fileItem = request.fileItem("avatar_file");
        JSONObject jsonObject = JSONObject.parseObject(avatar_data);
        FileOperation fileOperation = new FileOperation();
        System.out.println(fileItem);
        UserHook userHook = new UserHook();

        int[] flag = {1};

        Users user = request.session().attribute("name");
        String pathname = this.getClass().getClassLoader().getResource("").getPath();
//        String src = "target/classes/static/upload/img/";
        String src = pathname+"static/upload/img/";
        ActiveRecord activeRecord = new ActiveRecord();
        String imgName = String.valueOf(new Date().getTime());
        Users users = new Users();
        users.setM_id(user.getM_id());
        Users users1 = users.find();
        fileItem.ifPresent(item -> {
            byte[] data = item.getData();
            String type="";
            FileOutputStream fileOutputStream = null;
            try {
                fileOutputStream = new FileOutputStream(src+imgName+item.getFileName());
                fileOutputStream.write(data);
                fileOutputStream.close();
                type = FileOperation.getFileExt(src+imgName+item.getFileName());
                request.session().attribute("type","2."+type);

                if (jsonObject.getInteger("x")<0||jsonObject.getInteger("y")<0) {
                    response.json("{\"state\" : 500, \"result\" : \"选框超出图片边界了。\"}");
                    System.out.println("++++++++++++++++++++++++++++++++++++++++++选框超出图片边界了");
                    flag[0] = 0 ;
                }
                else {
                    if (fileOperation.cutImage(src+imgName+item.getFileName(), src + imgName + "2." + type, jsonObject.getInteger("x"),
                            Math.abs(jsonObject.getInteger("y")), jsonObject.getInteger("width"),
                            jsonObject.getInteger("height"), type,response)) {
                        fileOperation.deleteFile(src + imgName + item.getFileName());
                        activeRecord.execute("UPDATE member SET m_head_portrait = ? WHERE m_id=? ", imgName + "2." + type, user.getM_id());
                        if (!users1.getM_headPortrait().equals("default1.png")&&!users1.getM_headPortrait().equals("default2.png"))
                            fileOperation.deleteFile(src + users1.getM_headPortrait());
                        user.setM_headPortrait(imgName + "2." + type);
                        request.session().attribute("name", user);
                    }
                    else
                        flag[0] = 0 ;
                }
            }
            catch (IIOException ee){
                ee.printStackTrace();//支持各种格式图片上传
                response.json("{\"state\" : 500, \"result\" : \"图片格式有误！目前仅支持jpg和png格式图片上传。\"}");
                flag[0] = 0 ;
            }
            catch (IllegalArgumentException e){
                e.printStackTrace();
                response.json("{\"state\" : 500, \"result\" : \"选框超出图片边界了。\"}");
                flag[0] = 0 ;
            }
            catch (Exception e){
                e.printStackTrace();
                response.json("{\"state\" : 500, \"result\" : \"系统繁忙！\"}");
                flag[0] = 0 ;
            }
            finally {
                if (fileOutputStream!=null) {
                    try {
                        fileOutputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                fileOperation.deleteFile(src+imgName+item.getFileName());
            }
        });
        if (flag[0] == 1 ) {
            return imgName;
        }
        else
            return "false";
    }

    /**
     * @description 留言反馈
     * @param content
     * @param memberId
     */
    public void feedback(String content, int memberId) {
        Feedback feedback = new Feedback();
        feedback.setF_content(content);
        feedback.setF_time(date1);
        feedback.setF_menberid(memberId);
        feedback.save();
    }

    public void getVcode(Request request, Response response) {
        Vcode vcode = new Vcode();
        vcode.doGet(request, response);
    }

    public void sendEcode(Request request,String toEmail){
        Email email = new Email();
        String  ecode = String.valueOf((int)((Math.random()*9+1)*10000));
        request.session().attribute("ecode", ecode);
        ecode = "您的注册验证码："+ecode;
        String  content = "注册码";

        try {
            email.send_mail(toEmail, ecode, content);
            System.out.println("邮件发送成功!");
        } catch (MessagingException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    public boolean checkVcode(Request request,String vcode) {
        if (request.session().attribute("code").toString().toUpperCase().equals(vcode.toUpperCase())) {
            return true;
        }
        request.session().remove("code");
        return false;
    }

    public boolean checkEcode(Request request, String ecode) {
        if (request.session().attribute("ecode").toString().toUpperCase().equals(ecode.toUpperCase())) {
            return true;
        }
        request.session().remove("ecode");
        return false;
    }


    public boolean checkEmail(String email) {
        Users users = new Users();
        users.setM_email(email);
        if (users.find() != null) {
            return false;
        }
        return true;
    }

    public void dowanshan(Users member, Skills skills, Request request, Response response) {
        Integer uid = member.getM_id();
        Users users = new Users();
        users.setM_id(uid);
        users = users.find();
        if (member.getM_sex() == 2&&users.getM_headPortrait().equals("default1.png")) {
            member.setM_headPortrait("default2.png");
        }
        member.update("m_id", uid);
        Skills skill = new Skills();
        skill.setMemberid(uid);
        skill = skill.find();
        skills.execute("update skill set skillName1=?,skillContent1=?,skillName2=?,skillContent2=?,skillName3=?,skillContent3=?,skillName4=?,skillContent4=? where " +
                        " id=?",skills.getSkillName1(),skills.getSkillContent1(),skills.getSkillName2(), skills.getSkillContent2(),
                skills.getSkillName3(), skills.getSkillContent3(), skills.getSkillName4(), skills.getSkillContent4(), skill.getId());
    }

    public void sendLink(Request request, String toEmail,String domain)  {
        Email email = new Email();
        Md5 md5 = new Md5();
        Emailcode emailcode = new Emailcode();

        String code1 = String.valueOf((int)((Math.random()*9+1)*10000));
        String code =  md5.getMd5(toEmail + code1);

        emailcode.setE_mail(toEmail);
        emailcode.setE_code(code);
        emailcode.setE_date(date1);
        emailcode.save();
        String params = "forgotPassword?email=" + toEmail + "&code=" + code;
        try {
            InetAddress address = InetAddress.getLocalHost();
            String hostAddress = address.getHostAddress();
            String url = "http://"+domain+"/";
            email.send_mail(toEmail, "请在10分钟内点击下方链接完成重置密码：<br><a href=\""+url + params+"\">"+url + params+"</a><hr>注：若上方链接无法点开，请复制网址用浏览器访问。" ,"找回密码");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public boolean checkCode(Request request, String email, String code) {
        Emailcode emailcode = new Emailcode();
        emailcode.setE_mail(email);
        emailcode.setE_code(code);
        emailcode = emailcode.find();
        if (emailcode!=null) {
            return true;
        }
        return false;
    }

    public boolean checkRegister() {
        Register register = new Register();
        register.setR_id(1);
        register = register.find();
        if (register.getR_flag()==1) {
            return true;
        }
        else
            return false;
    }

    public void changePassword(Request request, String email, String password) {
        Md5 md5 = new Md5();
        Users users = new Users();
        password = md5.getMd5(password);
        users.setM_password(password);
        users.execute("UPDATE member SET m_password = ? WHERE m_email = ?", password, email);
    }

    public void domessage(String content, int memberId, int accepterId) {
        LeaveWord leaveWord = new LeaveWord();
        leaveWord.setL_content(content);
        leaveWord.setL_accepter(accepterId);
        leaveWord.setL_sender(memberId);
        leaveWord.setL_time(date1);
        leaveWord.save();
    }

    public void readmessage(int id) {
        LeaveWord leaveWord = new LeaveWord();
        leaveWord.setL_read(1);
        leaveWord.update("l_id",id);
    }
}
